package com.bnlr.lrparking.appui.order;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.blankj.utilcode.util.ToastUtils;
import com.bnlr.lrparking.app.Application;
import com.bnlr.lrparking.R;
import com.bnlr.lrparking.appui.sharevalue.recharge.SubmitSuccessActivity;
import com.bnlr.lrparking.appui.web.WebActivity;
import com.bnlr.lrparking.base.BaseActivity;
import com.bnlr.lrparking.app.AppConfig;
import com.bnlr.lrparking.constant.LrConstant;
import com.bnlr.lrparking.constant.Urls;
import com.bnlr.lrparking.event.ClosePayEvent;
import com.bnlr.lrparking.appui.bank.model.BankCardM;
import com.bnlr.lrparking.model.BaseBean;
import com.bnlr.lrparking.model.WxM;
import com.bnlr.lrparking.appui.order.mode.OrderIntentBean;
import com.bnlr.lrparking.constant.Params;
import com.bnlr.lrparking.util.pwddialog.SecurityEditCompileListener;
import com.bnlr.lrparking.util.pwddialog.SecurityPasswordEditText;
import com.bnlr.lrparking.view.CarCommon;
import com.bnlr.nohttp.CallServer;
import com.bnlr.nohttp.CustomHttpListener;
import com.tencent.mm.opensdk.modelpay.PayReq;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.yolanda.nohttp.NoHttp;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 订单车位保留金
 */
public class OrderRetentionMoneyActivity extends BaseActivity {
    private Unbinder unbinder;
    @BindView(R.id.tv_rertention_peice)
    TextView price;
    @BindView(R.id.tv_salesman)
    TextView tvSaleMan;
    @BindView(R.id.tv_salesman_phone)
    TextView tvSaleManPhone;
    @BindView(R.id.agree_clause)
    CheckBox agreeCheckBox;
    @BindView(R.id.textView4)
    TextView yue;
    @BindView(R.id.checkBox_retenwx)
    CheckedTextView ctvWX;
    @BindView(R.id.checkBox_retensy)
    CheckedTextView ctvSY;
    @BindView(R.id.tv_retention_btn)
    TextView tvSubmit;
    @BindView(R.id.tv_order_retention_rate)
    TextView tvRetentionRate;
    @BindView(R.id.tv_offline_pay)
    TextView tvOfflinePay;
    private OrderIntentBean item;
    private String incomeValue = "";
    private int clickTag = 0;
    private AlertDialog paydialog;
    private SecurityPasswordEditText editSecurityCode;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_retention_money);
        EventBus.getDefault().register(this);
        unbinder = ButterKnife.bind(this);

        item = getIntent().getParcelableExtra("order_bean");
        tvRetentionRate.setText("1、"+LrConstant.RATE_VALUE+"贡献值=人民币1元");
        getPersonInfo();
        if (item != null) {
            if (item.getType() == 4) {
                tvOfflinePay.setVisibility(View.GONE);
            }
            price.setText(item.getAdvanceMoney() + "");
            tvSaleMan.setText(TextUtils.isEmpty(item.getDealUserName())?"无":item.getDealUserName());
            tvSaleManPhone.setText(TextUtils.isEmpty(item.getDealPhone())?"无":item.getDealPhone());
            tvSubmit.setText("立即支付"+item.getAdvanceMoney() +"元");
        }


    }
    @OnClick({R.id.tv_issueagreement,R.id.rl_agree,R.id.tv_retention_btn,
            R.id.rely_retensy,R.id.rely_retenwx,R.id.id_retentionmoney,R.id.tv_offline_pay})
    public void retentionClick (View view) {
        switch (view.getId()) {
            case R.id.tv_issueagreement:
                Intent intent=new Intent(baseContext,WebActivity.class);
                intent.putExtra("tag",8);
                startActivity(intent);
                break;
            case R.id.rl_agree:
                if (agreeCheckBox.isChecked()) {
                    agreeCheckBox.setChecked(false);
                } else {
                    agreeCheckBox.setChecked(true);
                }
                break;
            //  微信支付
            case R.id.rely_retenwx:
                ctvWX.setChecked(false);
                ctvSY.setChecked(true);
                clickTag = 0;
                tvSubmit.setText("立即支付"+price.getText().toString() +"元");
                break;
            //  收益值支付
            case R.id.rely_retensy:
                ctvWX.setChecked(true);
                ctvSY.setChecked(false);
                clickTag = 1;
                tvSubmit.setText("立即支付"+Integer.parseInt(price.getText().toString())*LrConstant.RATE_VALUE +"收益值");
                break;
            case R.id.tv_retention_btn:
                if (agreeCheckBox.isChecked()) {
                    ToastUtils.showShort("请您先同意车位保留协议书");
                    return;
                }
                if (clickTag == 0) {
                    wxPay();
                } else {
                    if (item.getAdvanceMoney()*LrConstant.RATE_VALUE > Double.parseDouble(incomeValue)) {
                        ToastUtils.showShort("收益值不足");
                        return;
                    }
                    showPayDialog();
                }
                break;
            case R.id.id_retentionmoney:
                setBackMessage();
                break;
            case R.id.tv_offline_pay:
                offlinePay();
                break;
            default:
                break;
        }
    }

    private void offlinePay() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.ORDER, LrConstant.POST);
            mRequest.add("action", "PayAdvanceMoneyByOrder");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("orderId", item.getId());
            mRequest.add("type",4);
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BaseBean>(baseContext, true, BaseBean.class) {
                        @Override
                        public void doWork(BaseBean data, String code) {

                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (code.equals("1")) {
                                    startActivity(SubmitSuccessActivity.class);
                                    finish();
                                }else {
                                    ToastUtils.showShort(obj.getString("msg"));
                                    editSecurityCode.clearEdit();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    private void wxPay() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.ORDER, LrConstant.POST);
            mRequest.add("action", "PayAdvanceMoneyByOrder");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("appid",LrConstant.WX_APP_ID);
            mRequest.add("orderId", item.getId());
            mRequest.add("type",1);
            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<WxM>(baseContext, true, WxM.class) {
                        @Override
                        public void doWork(WxM data, String code) {
                            if (code.equals("1")) {
                                AppConfig.getInstance().putString("wx_order_id", data.getData().getOrderNo());
                                Params.PAY_FROM_TAG = 2;
                                doWXPay(data.getData());
                            }
                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (!code.equals("1")) {
                                    ToastUtils.showShort(obj.getString("msg"));
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    /**
     * 吊起微信
     * @param data
     */
    private void doWXPay(WxM.Data data) {

        PayReq request = new PayReq();
        request.appId = LrConstant.WX_APP_ID;
        request.partnerId = data.getPartnerid();
        request.prepayId= data.getPrepayid();
        request.packageValue = "Sign=WXPay";
        request.nonceStr= data.getNoncestr();
        request.timeStamp= data.getTimestamp();
        request.sign= data.getSign();
        request.extData = "app data";
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ToastUtils.showShort("微信支付获取中....");
            }
        });

        boolean isPaySupported = Application.mWxApi.isWXAppInstalled();
        if(!isPaySupported){
            ToastUtils.showShort("手机不支持微信支付");
            return;
        }
        Application.mWxApi.sendReq(request);
    }

    /**
     * 支付弹框
     */
    public void showPayDialog() {
        paydialog = new AlertDialog.Builder(this).create();
        paydialog.setCanceledOnTouchOutside(false);
        paydialog.setView(new EditText(this));
        paydialog.show();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if(editSecurityCode!=null){
                    //设置可获得焦点
                    editSecurityCode.getEditText().setFocusable(true);
                    editSecurityCode.getEditText().setFocusableInTouchMode(true);
                    //请求获得焦点
                    editSecurityCode.getEditText().requestFocus();
                    //调用系统输入法
                    InputMethodManager inputManager = (InputMethodManager) editSecurityCode.getEditText()
                            .getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputManager.showSoftInput(editSecurityCode.getEditText(), 0);
                }
            }
        }, 200);

        Window window = paydialog.getWindow();
        window.clearFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
        window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        paydialog.setContentView(R.layout.activity_input_password_dialog);

        final RelativeLayout pay_back=(RelativeLayout)window.findViewById(R.id.pay_back);
        pay_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                paydialog.dismiss();
            }
        });
        editSecurityCode = (SecurityPasswordEditText) window
                .findViewById(R.id.security_linear);
        editSecurityCode.setSecurityEditCompileListener(new SecurityEditCompileListener() {
            @Override
            public void onNumCompleted(String num) {
                earnPay(num);
            }
        });
    }

    /**
     * 收益值支付
     * @param password
     */
    private void earnPay(String password) {
        try {
            mRequest = NoHttp.createStringRequest(Urls.ORDER, LrConstant.POST);
            mRequest.add("action", "PayAdvanceMoneyByOrder");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            mRequest.add("orderId", item.getId());
            mRequest.add("type",2);
            mRequest.add("payPassword",password);

            CallServer.getRequestInstance().add(baseContext, mRequest,
                    new CustomHttpListener<BankCardM>(baseContext, true, BankCardM.class) {
                        @Override
                        public void doWork(BankCardM data, String code) {

                        }
                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if (code.equals("1")) {
                                    ToastUtils.showShort("支付成功");
                                    finish();
                                }else {
                                    ToastUtils.showShort(obj.getString("msg"));
                                    editSecurityCode.clearEdit();
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, true);
        } catch (Exception e) {
        }
    }

    /**
     * 获取贡献值  收益值
     */
    private void getPersonInfo() {
        try {
            mRequest = NoHttp.createStringRequest(Urls.IP, LrConstant.POST);
            mRequest.add("action", "GetUserInfoById");
            mRequest.add("phonePara", Application.DEVICE_ID);
            mRequest.add("uid", AppConfig.getInstance().getString("uid", ""));
            // 添加到请求队列
            CallServer.getRequestInstance().add(this, mRequest,
                    new CustomHttpListener<JSONObject>(this, false, null) {
                        @Override
                        public void doWork(JSONObject data, String code) {
                        }

                        @Override
                        public void onFinally(JSONObject obj, String code, boolean isSucceed) {
                            try {
                                super.onFinally(obj, code, isSucceed);
                                if ("1".equals(code)) {
                                    JSONObject object = obj.getJSONObject("data");
                                    //收益值
                                    incomeValue = object.getString("incomevalue")+"";
                                    yue.setText("(剩余"+incomeValue+"收益值)");
                                } else {

                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }, false);
        } catch (Exception e) {

        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void closeActivity (ClosePayEvent event) {
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        unbinder.unbind();
    }
    private void setBackMessage(){
        CarCommon carCommon = new CarCommon();
        carCommon.CommonDialog(this,"此车位将被其他用户订购，如您现在交定金，车位将为您保留，定金7日内可退款","确定不交定金吗？");
        carCommon.setClickSureListener(new CarCommon.ClickSureListener() {
            @Override
            public void setSure() {
                finish();
            }
        });
    }

    @Override
    public void onBackPressed() {
        setBackMessage();
    }
}
